import sdk from '../index';
// 战斗核心类 - 封装战斗逻辑的 SDK 接口
import { BattleArea, BattleEndData } from './battleArea';
import { BaseBody } from './entity/body_base';
import { killLog } from './types';
import { Item } from '../../shared/face/index';
import { wordMap } from './wordMap';
import player from './entity/player';
import { ComType } from '../tool/component';
import rpg_component from '../../component/rpg_component';
import client_component from '../../component/client_component';
import { TaskTargetType } from './types/task';

/**
 * 战斗核心类
 * 提供简洁的战斗 API，隐藏底层复杂性
 */
export class BattleCore {
    private battleArea: BattleArea;

    constructor() {
        this.battleArea = new BattleArea();
    }

    /**
     * 添加单位到战场
     * @param unit 战斗单位
     * @param isHome 是否为主场单位（true: 主场, false: 客场）
     * @returns 当前实例，支持链式调用
     */
    addUnit(unit: BaseBody, isHome: boolean): BattleCore {
        this.battleArea.addUnit(unit, isHome);
        return this;
    }

    /**
     * 设置击杀回调
     * @param callback 击杀事件回调函数
     * @returns 当前实例，支持链式调用
     */
    onKill(callback: (killLog: killLog, battleCore: BattleCore) => void): BattleCore {
        this.battleArea.setOnKill((killLog, battleArea) => {
            callback(killLog, this);
        });
        return this;
    }

    /**
     * 为指定单位添加奖励
     * @param unit 目标单位
     * @param reward 奖励物品
     * @returns 当前实例，支持链式调用
     */
    addReward(unit: any, reward: Item | Item[]): BattleCore {
        this.battleArea.addReward(unit, reward);
        return this;
    }

    /**
     * 开始战斗
     * @param onEnd 战斗结束回调
     * @param dev 是否为开发模式
     * @returns 当前实例，支持链式调用
     */
    start(onEnd: (data: BattleEndData) => void, dev: boolean = false): BattleCore {
        this.battleArea.startBattle(onEnd, dev);
        return this;
    }

    /**
     * 获取当前回合数
     * @returns 回合数
     */
    getRound(): number {
        return this.battleArea.getRound();
    }

    /**
     * 获取原始的 BattleArea 实例（供高级用户使用）
     * @returns BattleArea 实例
     */
    getRawBattleArea(): BattleArea {
        return this.battleArea;
    }

    /**
     * 获取战斗统计信息
     * @returns 统计信息
     */
    getStats() {
        return {
            playerStats: this.battleArea.getPlayerStats(),
            playerLogs: this.battleArea.getPlayerLogs(),
            round: this.battleArea.getRound()
        };
    }

    /**
     * 从地图创建战斗（静态方法）
     * @param map 地图实例
     * @param targetUnit 目标单位
     * @returns 战斗创建结果
     */
    static createFromMap(map: wordMap, targetUnit: BaseBody): {
        success: boolean;
        message: string;
        battleCore?: BattleCore;
    } {
        if (!map) {
            return {
                success: false,
                message: '地图未初始化'
            };
        }

        try {
            // 获取目标单位所在的格子
            const cell = map.checkPos(targetUnit);
            if (!cell) {
                return {
                    success: false,
                    message: '目标单位不在地图上'
                };
            }

            const battleCore = new BattleCore();
            let team = { a: 0, b: 0, players: [] as player[] };
            
            // 遍历格子中的所有单位
            for (let i = 0; i < cell.unitMap.length; i++) {
                let unit = cell.unitMap[i];
                let rpgCom = unit.getComponent(ComType.rpg) as rpg_component;
                
                // 跳过死亡单位
                if (rpgCom.isDie()) {
                    continue;
                }
                
                // 记录玩家
                if (unit instanceof player) {
                    team.players.push(unit as player);
                }
                
                // 分配阵营
                if (unit.id === targetUnit.id) {
                    battleCore.addUnit(unit, true);  // 主场
                    team.a++;
                } else {
                    battleCore.addUnit(unit, false); // 客场
                    team.b++;
                }
            }
            
            // 检查战斗条件
            if (team.a === 0 || team.b === 0) {
                const msg = '战斗失败:有一方人数为0无法开始战斗';
                for (let i = 0; i < team.players.length; i++) {
                    let clientCom = team.players[i].getComponent(ComType.client) as client_component;
                    clientCom.client_text(msg);
                }
                return {
                    success: false,
                    message: msg
                };
            }

            // 设置默认击杀奖励
            battleCore.onKill((killLog, battleCore) => {
                const reward = sdk.prop.PolicyReward_击杀('野外击杀怪物', killLog, map.name);
                battleCore.addReward(killLog.unit, reward);
                
                // 更新世界任务进度
                const taskComponent = killLog.unit.getComponent(ComType.任务) as any;
                if (taskComponent) {
                    taskComponent.updateWorldTaskProgress(killLog.unit, TaskTargetType.击杀怪物, killLog.target.id);
                }
            });

            return {
                success: true,
                message: '战斗创建成功',
                battleCore
            };
        } catch (error) {
            return {
                success: false,
                message: '创建战斗失败'
            };
        }
    }
} 